import React, { useState, useEffect } from 'react';
import { withRouter } from 'react-router-dom'
import { NavBar, Icon, List, TextareaItem, Modal, Toast, Accordion, Button } from 'antd-mobile';
import { CancelOrder, ParentOrderDetails, NO_DEAL, CancelChooseApply } from "@/api/order/order.js"
import { previewPict } from "@/api/login";
import buildSteps from "./common";
import { R, ORDER_STATUSES, createInfoWindow, VOID } from "@/assets/js/dict.js"
import './orderDetails.scss';
import _ from "lodash";

import AMap from 'AMap';
import mark from "@/assets/svg/mark.svg"

const confirm = Modal.alert;

const Item = List.Item;
const Brief = Item.Brief;


/* 状态：已发布、已选中、已接单、试讲
* 已经发布的订单，有操作的：
* 1、查看已经报名，列表、详情
* 2、选择已经报名的，初步选中报名者
* 3、取消选择报名者，若报名者已经支付了中介费，则操作失败
* 4、线下交流未果，交易失败
* */
function OrderDetailsOfPublish (props) {
    let [OrderDetailsData, setOrderDetailsData] = useState({
        applies: [],
        students: [],
        student_ids: "",
        teacher: {},
        learn_hours: "[]"
    }); // 相当于 this.state
    let [order_id, setOrder_id] = useState(props.order_id);
    let [status, setStatus] = useState("");

    let [flush, goFlush] = useState(""),
        [userInfo] = useState(() => {
            let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
            return userInfo
        });
    let [showCloseOrder, setShowCloseOrder] = useState(false);
    let [closeOrderComment, setCloseOrderComment] = useState("");

    function wakeupCloseOrder () {
        setShowCloseOrder(true);
    }

    function hideCloseOrder () {
        setShowCloseOrder(false);
    }

    /*
    * 刷新本页
    * */
    function doFlush () {
        goFlush(new Date().getTime());
    }

    /*
    * 取消已经选中的家教
    * */
    function cancelChooseApply () {
        confirm('取消选中的家教', '确定要取消选中的家教吗', [
            {
                text: '放弃', onPress: () => {
                }
            },
            {
                text: '确定', onPress: () => {
                    let postDate = {
                        order_id: OrderDetailsData.id,
                        parent_id: userInfo.id,
                        tutor_id: OrderDetailsData.tutor_id,
                    };
                    CancelChooseApply(postDate, (res) => {
                        if (R.isSuccess(res)) {
                            Toast.success("操作成功", 3, () => {
                                sessionStorage.removeItem("applyInfo");
                                doFlush();
                            }, false);
                        }
                    });
                }
            },
        ]);
    }

    /*
    * 取消已经选中的家教
    * */
    function closeOrder () {
        let postDate = {
            order_id: OrderDetailsData.id,
            comment: closeOrderComment,
        };
        NO_DEAL(postDate, (res) => {
            if (R.isSuccess(res)) {
                Toast.success("操作成功", 3, () => {
                    sessionStorage.removeItem("order_id");
                    props.history.push("/lookForTutor");
                }, false);
            }
        });

    }

    /**
     * 撤回订单
     */
    function cancel () {
        confirm('撤回订单', '确定要撤回订单吗', [
            { text: '取消', onPress: () => console.log('cancel') },
            {
                text: '撤回', onPress: () => {
                    CancelOrder({ order_id: order_id }, (res) => {
                        if (res[R.code] === R.success) {
                            Toast.success("操作成功", 3, () => {
                                sessionStorage.removeItem("order_id");
                                props.history.push("/lookForTutor");
                            }, false);
                        } else {
                            Toast.fail("操作异常：" + res[R.msg]);
                        }
                    });
                }
            },
        ]);
    }


    function getOrderDetails () {
        let obj = props.OrderDetailsData;
        let order_id;
        if (!!obj) {
            order_id = obj.id;
        } else {
            order_id = sessionStorage.getItem("order_id");
        }

        ParentOrderDetails({ order_id: order_id }, (res) => {
            if (R.isSuccess(res)) {
                let data = R.getData(res);
                setStatus(data.status);
                setOrder_id(order_id);
                setOrderDetailsData(data);

                //展示地图
                if (null !== data.longitude && null !== data.latitude) {
                    let mapInstance = new AMap.Map('amap', {
                        resizeEnable: true,
                        zoomEnable: false,
                        dragEnable: true,
                        center: [data.longitude, data.latitude],//传入地址的经纬度
                        zoom: 13
                    });
                    mapInstance.on('complete', function () {
                        AMap.plugin(['AMap.Geocoder', 'AMap.Marker', 'AMap.LngLat', 'AMap.Pixel', 'AMap.Icon', 'AMap.OverlayGroup', 'AMap.Autocomplete'], () => {
                            let markPoint = new AMap.Marker({
                                position: new AMap.LngLat(data.longitude, data.latitude),
                                offset: new AMap.Pixel(-10, -10),
                                icon: mark, // 添加 Icon 图标 URL
                                title: '教学地址',
                                label: {
                                    // content: '<span style="color: darkgreen; font-size: x-large"><strong>选中的地址</strong></span>'
                                }
                            });

                            let geocoder = new AMap.Geocoder({
                                city: "", //城市设为北京，默认：“全国”
                                radius: 1000 //范围，默认：500
                            });

                            let address = ''; // 点击坐标的详细地址；

                            geocoder.getAddress([data.longitude, data.latitude], (status, result) => {
                                if (status === 'complete' && result.regeocode) {
                                    address = result.regeocode.formattedAddress;

                                    //实例化信息窗体
                                    let title = '详细地址：',
                                        content = [];
                                    content.push(address);

                                    //构建自定义信息窗体
                                    let infoWindow = new AMap.InfoWindow({
                                        position: new AMap.LngLat(data.longitude, data.latitude),
                                        offset: new AMap.Pixel(24, -4),
                                        autoMove: true,
                                        isCustom: true,  //使用自定义窗体
                                        content: createInfoWindow(title, content.join("<br/>"), mapInstance),
                                    });

                                    infoWindow.open(mapInstance)
                                } else {
                                    console.error('根据经纬度查询地址失败')
                                }
                            });

                            //添加标识物
                            mapInstance.add(markPoint);
                        });
                    });
                }
            }
        });
    }

    useEffect(getOrderDetails, [flush]);

    /**
     * 展示已经报名的信息
     */
    function appliesRender () {

    }

    /**
     * 跳转到学生的详情页
     * @param id
     */
    function goStudentDetails (id) {
        console.log("id--->", id);
        sessionStorage.setItem("student_id", id);
        props.history.push("/studentDetails");
    }

    function back () {
        props.history.goBack();
    }


    return (
        <div className="orderDetails">
            <div className="page-title  home-tit">
                <NavBar
                    mode="light"
                    icon={<Icon type="left" />}
                    leftContent={<span key="rc"></span>}
                    // rightContent={[
                    //     <span key={"cz"} onClick={showActionSheet}>操作</span>
                    // ]}
                    onLeftClick={back}
                >
                    待定订单
                </NavBar>
            </div>

            <div className="page-content  home-content">
                <div className="publish-content-piece">
                    <div className="form-box">
                        <div
                            style={{ display: OrderDetailsData.status != ORDER_STATUSES.EDITING || OrderDetailsData.status != ORDER_STATUSES.AUDITING ? 'block' : 'none' }}>
                            <p style={{ color: 'red' }}>如需修改或编辑订单，请联系客服人员。</p>
                        </div>
                        <div className="form-con">
                            {buildSteps(status)}
                        </div>
                        <div className="status-style">
                            订单状态:
                            <b>{OrderDetailsData.status}</b>
                        </div>
                        <div className="form-tit"
                            style={{ display: (OrderDetailsData.applies.length > 0 ? 'block' : 'none') }}
                        >
                            <i className="mini-block" />
                            <strong>
                                已经报名的家教
                            </strong>
                        </div>
                        <div className="form-con"
                            style={{ display: (OrderDetailsData.applies.length > 0 ? 'block' : 'none') }}>
                            <List>
                                {
                                    OrderDetailsData.applies.map((item, index) => {
                                        item.order_id = OrderDetailsData.id;
                                        return <Item className="to-resume" arrow="horizontal" key={`list${index}`} extra="查看家教简历"
                                            onClick={() => {
                                                let params = _.cloneDeep(item);
                                                params.order_id = OrderDetailsData.id;
                                                params.order_status = OrderDetailsData.status;
                                                sessionStorage.setItem("applyInfo", JSON.stringify(params));
                                                let path = { params: params, pathname: "/orderDetailsOfSelect" };
                                                props.history.push(path);
                                            }}>
                                            <img className="head-img" src={previewPict(item.pict)}
                                            />
                                            <div >
                                                姓名：{item.name}
                                                <br />
                                                性别：{item.gender}
                                            </div>
                                        </Item>
                                    })
                                }

                            </List>
                        </div>
                        <div className="form-tit"
                            style={{ display: (!!OrderDetailsData.teacher && OrderDetailsData.status === ORDER_STATUSES.SELECTED) ? 'block' : 'none' }}
                        >
                            <i className="mini-block" />
                            <strong>
                                已经选中的家教
                            </strong>
                        </div>
                        <div className="form-con"
                            style={{ display: (!!OrderDetailsData.teacher ? 'block' : 'none') }}>
                            {!!OrderDetailsData.teacher ?
                                <List>
                                    <Item arrow="horizontal" key={`list$`} extra="查看家教简历"
                                        onClick={() => {
                                            let params = _.cloneDeep(OrderDetailsData.teacher);
                                            params["order_id"] = OrderDetailsData.id;
                                            params.tutor_id = OrderDetailsData.teacher.id;
                                            params.order_status = OrderDetailsData.status;
                                            sessionStorage.setItem("applyInfo", JSON.stringify(params));
                                            let path = {
                                                params: params,
                                                pathname: "/orderDetailsOfSelect"
                                            };
                                            props.history.push(path);
                                        }}>
                                        <img className="head-img" src={previewPict(OrderDetailsData.teacher.pict)}
                                        />
                                        <Brief>姓名：{OrderDetailsData.teacher.name}</Brief>
                                        <Brief>性别：{OrderDetailsData.teacher.gender}</Brief>
                                        <Brief>学院：{OrderDetailsData.teacher.school}</Brief>
                                    </Item>
                                </List>
                                : ''}
                        </div>
                        <div className="form-tit">
                            <i className="mini-block" />
                            <strong>
                                基本信息
                            </strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <List.Item
                                    extra={OrderDetailsData.parent_name}
                                >家长姓名</List.Item>
                                <List.Item
                                    extra={OrderDetailsData.parent_gender}
                                >家长性別</List.Item>
                                <List.Item
                                >课时费<Brief>{OrderDetailsData.class_fee ? "￥" + OrderDetailsData.class_fee / 100 : ''} （暂定）</Brief>
                                </List.Item>
                                <List.Item
                                >
                                    辅导科目<List.Item.Brief>{OrderDetailsData.subjects}</List.Item.Brief>
                                </List.Item>
                            </List>
                        </div>
                        <div className="form-tit">
                            <i className="mini-block" />
                            <strong>
                                可授课时间段
                            </strong>
                        </div>
                        <div className="form-con">
                            <Accordion defaultActiveKey="0" className="my-accordion">
                                {
                                    JSON.parse(OrderDetailsData.learn_hours).length ?
                                        JSON.parse(OrderDetailsData.learn_hours).map((item, index) => {
                                            return <Accordion.Panel header={
                                                <div>
                                                    {item.week}
                                                </div>
                                            } key={index}>
                                                <List className="my-list">
                                                    <Item extra={item.startTime}>开始日期</Item>
                                                    <Item extra={item.endTime}>结束日期</Item>
                                                </List>
                                            </Accordion.Panel>
                                        })
                                        :
                                        ''
                                }
                            </Accordion>
                        </div>
                        <div className="form-tit">
                            <i className="mini-block" />
                            <strong>
                                上课地址
                            </strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <Item
                                >地址<Brief>{OrderDetailsData.learn_address}</Brief></Item>
                            </List>
                            <div id="amap" style={{ width: '100%', height: '300px' }} />
                        </div>
                        <div className="form-tit">
                            <i className="mini-block" />
                            <strong>学生</strong>
                        </div>
                        <div className="form-con">
                            <List>
                                {OrderDetailsData.students.map((item, index) => {
                                    return (
                                        <Item key={index}
                                            arrow="empty"
                                            multipleLine
                                            platform="cross"
                                        >
                                            名称：{item.name}
                                            <Brief> 年龄：{item.age}</Brief>
                                            <Brief> 年级：{item.grade}</Brief>
                                            <Brief> 说明：{item.note}</Brief>
                                        </Item>
                                    )
                                })}
                            </List>
                        </div>
                        <div className="form-tit">
                            <i className="mini-block" />
                            <strong>对家教老师的要求</strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <TextareaItem
                                    editable="false"
                                    disabled
                                    value={OrderDetailsData.demand}
                                    autoHeight
                                    rows={5}
                                />
                            </List>
                        </div>
                        <Button style={{
                            color: 'red',
                            display: OrderDetailsData.status === ORDER_STATUSES.AUDITING ? 'block' : 'none'
                        }}
                            onClick={cancel}>撤回订单</Button>
                        <Button type="primary" style={{
                            color: 'red',
                            display: OrderDetailsData.status === ORDER_STATUSES.SELECTED ? 'block' : 'none'
                        }}
                            onClick={cancelChooseApply}
                        >取消选中家教</Button>
                        <Button type="primary" style={{
                            color: 'red',
                            display: OrderDetailsData.status === ORDER_STATUSES.PAYED ? 'block' : 'none'
                        }} onClick={wakeupCloseOrder}
                        >交流不畅，关闭订单</Button>
                    </div>
                </div>
            </div>

            <Modal
                popup
                visible={showCloseOrder}
                maskClosable
                title={<h4><strong>关闭订单</strong></h4>}
                message={"提示：关闭的订单将失效，并归入历史订单"}
                animationType="slide-up"
                onClose={hideCloseOrder}
                footer={[{
                    style: {
                        color: '#fff',
                        border: '1PX solid #e94f4f',
                        borderRadius: '5PX',
                        backgroundColor: '#e94f4f'
                    }, text: '取消', onPress: hideCloseOrder
                }, {
                    style: {
                        color: '#fff',
                        border: '1PX solid #108ee9',
                        borderRadius: '5PX',
                        backgroundColor: '#108ee9'
                    }, text: '确定', onPress: closeOrder
                }]}
            >
                <List>
                    <TextareaItem
                        placeholder="关闭订单的说明"
                        rows={7}
                        clear
                        count={200}
                        onChange={setCloseOrderComment}
                    />
                </List>
            </Modal>
        </div>
    );
}

export default withRouter(OrderDetailsOfPublish);